<script setup>
import {
  FolderAdd,
  EditPen,
  DeleteFilled,
  RemoveFilled,
  CirclePlusFilled,
  WarnTriangleFilled
} from "@element-plus/icons-vue"

import {onMounted, reactive, ref} from "vue";
import {getRaceListService} from "@/api/race.js";
import {ElMessage, ElMessageBox} from "element-plus";
import router from "@/router/index.js";
import {
  deleteContestOjQuestionService,
  deleteContestService,
  publishContestService,
  revokePublishContestService
} from "@/api/contest.js";

const totalSize = ref(0)
// 竞赛列表
const raceList = ref([])
// 时间选择器响应式数组
const datetimeRange = ref([])
const formParams = reactive({
  current: 1,
  size: 10,
  title: "",
  beginTime: "",
  endTime: ""
})

//开赛时间与当前时间相比，大于当前时间就开始比赛了
function isNotStartExam(param) {
  const nowData = new Date();
  return new Date(param.beginTime) > nowData;
}

// 判断竞赛的结束时间与当前时间相比
function isNotEndExam(param) {
  const nowData = new Date();
  return new Date(param.endTime) > nowData;
}

async function handleChange() {
  const raceListResult = await getRaceListService(formParams)
  raceList.value = raceListResult.data.records
  totalSize.value = raceListResult.data.total
}

onMounted(async () => {
  await handleChange()
})

function handleSizeChange() {
  formParams.current = 1
  handleChange()
}

function handleCurrentChange() {
  handleChange()
}

function onStopRace() {
  ElMessage({
    message: '已开赛，禁止操作！',
    type: 'info',
    plain: true,
  })
}

function onSearch() {
  if (formParams.title.toString().trim() === "") {
    ElMessage({
      message: '请输入要搜索竞赛标题，再进行查询！',
      type: 'warning',
    })
    return;
  }
  formParams.current = 1
  handleChange()
}

function onReset() {
  formParams.current = 1
  formParams.size = 10
  formParams.title = ""
  formParams.beginTime = ""
  formParams.endTime = ""
  datetimeRange.value.length = 0
  handleChange()
}

function onTimeChange() {
  if (datetimeRange.value[0] instanceof Date) {
    formParams.beginTime = datetimeRange.value[0].toISOString()
  }

  if (datetimeRange.value[1] instanceof Date) {
    formParams.endTime = datetimeRange.value[1].toISOString()
  }
  handleChange()
}

function onAddRace() {
  // 跳转到添加竞赛页面
  router.push("/admin/system/updateRace?type=add")
}

function onEdit(id) {
  router.push(`/admin/system/updateRace?type=edit&id=${id}`)
}

async function onDelete(id) {
  try {
    await ElMessageBox.confirm(
        '确定要删除竞赛详情吗?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
    const deleteForm = reactive({
      id: id
    })
    await deleteContestService(deleteForm)
    formParams.current = 1
    await handleChange()
    ElMessage.success("删除该竞赛详情成功")
  } catch (error) {
    if (error === "cancel") {
    }
  }
}

async function publishContest(id) {
  try {
    await ElMessageBox.confirm(
        '确定要发布该竞赛吗?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
    const publishForm = reactive({
      id: id
    })
    await publishContestService(publishForm)
    ElMessage.success("发布竞赛成功")
    await handleChange()
  } catch (error) {
    if (error === "cancel") {
    }
  }
}

async function revokePublishContest(id) {
  try {
    await ElMessageBox.confirm(
        '确定要取消发布该竞赛吗?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
    const publishForm = reactive({
      id: id
    })
    await revokePublishContestService(publishForm)
    ElMessage.success("取消分布竞赛成功")
    await handleChange()
  } catch (error) {
    if (error === "cancel") {
    }
  }
}
</script>

<template>
  <el-form inline="true">
    <el-form-item label="创建日期">
      <el-date-picker @change="onTimeChange" v-model="datetimeRange" style="width: 240px" type="datetimerange"
                      range-separator="至"
                      start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
    </el-form-item>
    <el-form-item label="竞赛名称">
      <el-input v-model="formParams.title" placeholder="请您输入要搜索的竞赛名称" @keydown.enter="onSearch"/>
    </el-form-item>
    <el-form-item>
      <el-button @click="onSearch" plain>搜索</el-button>
      <el-button @click="onReset" plain type="info">重置</el-button>
      <el-button type="primary" :icon="FolderAdd" plain @click="onAddRace">添加竞赛</el-button>
    </el-form-item>
  </el-form>
  <!-- 表格 -->
  <el-table height="626px" :data="raceList">
    <el-table-column prop="title" label="竞赛标题"/>
    <el-table-column prop="beginTime" width="180px" label="竞赛开始时间"/>
    <el-table-column prop="endTime" width="180px" label="竞赛结束时间"/>
    <el-table-column label="是否开赛" width="100px">
      <template #default="{ row }">
        <div v-if="!isNotStartExam(row)">
          <el-tag type="warning">已开赛</el-tag>
        </div>
        <div v-else>
          <el-tag type="info">未开赛</el-tag>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="是否完赛" width="100px">
      <template #default="{ row }">
        <div v-if="!isNotEndExam(row)">
          <el-tag type="danger">已完赛</el-tag>
        </div>
        <div v-else>
          <el-tag type="primary">未完赛</el-tag>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="adminUser" width="140px" label="创建用户"/>
    <el-table-column prop="createTime" width="180px" label="创建时间"/>
    <el-table-column prop="updateTime" width="180px" label="修改时间"/>
    <el-table-column prop="status" width="100px" label="是否发布">
      <template #default="{ row }">
        <div v-if="row.status == 0">
          <el-tag type="danger">未发布</el-tag>
        </div>
        <div v-if="row.status == 1">
          <el-tag type="success">已发布</el-tag>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="180px">
      <template #default="{ row }">
        <el-button v-if="isNotStartExam(row) && row.status == 0" type="text" title="编辑竞赛" @click="onEdit(row.id)"
                   :icon="EditPen"></el-button>
        <el-button v-if="isNotStartExam(row) && row.status == 0" type="text" title="删除竞赛" @click="onDelete(row.id)"
                   class="red"
                   :icon="DeleteFilled"></el-button>
        <el-button v-if="row.status == 1 && isNotStartExam(row)" type="text" title="取消发布"
                   @click="revokePublishContest(row.id)"
                   :icon="RemoveFilled"></el-button>
        <el-button v-if="row.status == 0 && isNotStartExam(row)" type="text" title="发布竞赛"
                   @click="publishContest(row.id)"
                   :icon="CirclePlusFilled"></el-button>
        <el-button type="text" v-if="!isNotStartExam(row)" :icon="WarnTriangleFilled" title="禁止操作"
                   @click="onStopRace"></el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页区域 -->
  <el-pagination background size="small"
                 :total="totalSize"
                 layout="total, sizes, prev, pager, next, jumper"
                 v-model:current-page="formParams.current"
                 v-model:page-size="formParams.size"
                 :page-sizes="[1, 5, 10, 15, 20]"
                 @size-change="handleSizeChange"
                 @current-change="handleCurrentChange"/>
</template>

<style scoped>
</style>